const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
// 处理接口post的请求
const bodyparser = require('koa-bodyparser')
// 打印日志
const logger = require('koa-logger')

// koa-generic-session、koa-redis还没安装
const session = require('koa-generic-session')
const Redis = require('koa-redis')

const mongoose = require('mongoose')
const dbConfig = require('./dbs/config')
const passport = require('./interface/utils/passport')

const index = require('./routes/index')
// const users = require('./routes/users')
const users = require('./interface/users')
const userManagement = require('./interface/userManagement')


// error handler
onerror(app)

// 用于session做加密处理的，[]中这两个值可以随便写
app.keys = ['mt', 'keyskeys']
app.proxy = true
app.use(session({
    key: 'mt',
    prefix: 'mt:uid',
    // 如果这里不写则session默认存储在内存中，这里我们存进Redis
    store: new Redis() // redis不用配置参数，默认指向本机redis
}))


// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// 链接数据库
mongoose.connect(dbConfig.dbs,{
  useNewUrlParser: true,
  useUnifiedTopology: true
})
// passport初始化
app.use(passport.initialize())
app.use(passport.session())

// routes
app.use(index.routes(), index.allowedMethods())
// app.use(users.routes(), users.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(userManagement.routes(), userManagement.allowedMethods())


// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

app.listen(8082, ()=> {
  console.log('链接成功！')
})
module.exports = app
